<template>
  <div>
    <h2>难度设置</h2>
    <el-form :model="formData" ref="form" label-width="100px">
      <el-form-item
        label="最大难度"
        prop="max"
        :rules="[
          { required: true, message: '请输入'}
        ]"
      >
        <el-input type="number" @change="changeMax" v-model.number="formData.max" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="题目个数"
        prop="total"
        :rules="[
          { required: true, message: '请输入'}
        ]"
      >
        <el-input type="number" v-model.number="formData.total" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  export default {
    name: 'setting',
    data() {
      return {
        formData: {
          max: '',
          total: ''
        }
      }
    },
    computed: {
      ...mapState({
        max: state => state.exam.max,
        total: state => state.exam.total
      })
    },
    methods: {
      changeMax(max) {
        if (max < 10) {
          this.formData.max = 10
        }
      },
      submitForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const {max, total} = this.formData
            this.$store.commit('SET_EXAM', {
              max,
              total
            })
            this.$message.success('成功修改配置')
          }
        })
      },
      setDefault() {
        this.formData.max = this.max
        this.formData.total = this.total
      }
    },
    mounted() {
      this.setDefault()
    }
  }
</script>
